-- plantuml_kroki_filter.lua
-- Processes ```plantuml code blocks by generating image URLs pointing to the Kroki.io service.
-- Requires internet connection when viewing the final HTML to load images.

local kroki_server = "https://kroki.io" -- Public Kroki instance
local diagram_type = "plantuml"
local output_format = "svg" -- 'svg' or 'png'

-- Helper function to encode string to URL-safe Base64 (no padding)
-- Based on https://github.com/iskolbin/lbase64 but adapted for URL safety and no padding
local function base64_url_encode(data)
  local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' -- URL safe alphabet
  local encoded = ((data:gsub('.', function(x)
      local r,b='',x:byte()
      for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
      return r;
  end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
      if (#x < 6) then return '' end
      local c=0
      for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
      return b:sub(c+1,c+1)
  end))
  -- Remove padding
  encoded = encoded:gsub("=*", "")
  return encoded
end


-- Function called by Pandoc for each CodeBlock element
function CodeBlock(el)
    print("-----1112---")
  -- Check if the code block has the 'plantuml' class
  if el.classes[1] == diagram_type then
    local code = el.text

    -- Check if the code is empty
    if code:match("^%s*$") then
      -- Return a placeholder or empty paragraph if code is empty
      return pandoc.Para(pandoc.Emph(pandoc.Str("[Empty PlantUML block]")))
    end

    -- Encode the PlantUML code using URL-safe Base64
    local encoded_code = base64_url_encode(code)
    print(encoded_code)
    print("-----1112---")
    -- Construct the Kroki URL
    local image_url = string.format("%s/%s/%s/%s",
                                  kroki_server,
                                  diagram_type,
                                  output_format,
                                  encoded_code)

    print(image_url)
    -- Return a Pandoc Image element pointing to the Kroki URL
    -- Image(attr, caption, target) where target is {url, type}
    -- Alt text is set to "PlantUML Diagram"
    local img_html = pandoc.RawBlock('html', string.format('<img src="data:image/svg+xml;base64,%s">', base64_contents))
    print("return ing...")
    return img_html
  end

  -- If it's not a plantuml block, return nil to let Pandoc handle it normally
  return nil
end